/*****
 * socket 管理
 * author: sailing
 * *****/
import io from 'socket.io-client';
import eventBus from './eventBus';
import localstorage from '../server/localstorage';
class socketMrg {
  public socketList: any = [];
  public socket: any;

  constructor() {
    // this.mySocket = io("http://127.0.0.1:7001");
    // this.socket = io('http://192.168.10.41:7001');
    this.socket = io('https://mobile.linkpc.cn/');
    // this.socket.emit("message", "hello world");
    this.eventReg();
  }
  public set(id: string) {
    console.log('set userID');
  }

  public eventReg() {
    const self = this;
    this.socket.on('message', (message: any) => {
      // alert("oooo");
      console.log('收到消息 <<<<<<<<<<<<<<<<', message.type, message);
      if (message.type) {
        eventBus.$emit(message.type, message.data);
        eventBus.$emit('debug', {
          mtype: 'recive',
          msg: message,
        });
      }
      // eventBus.$emit()
    });

    this.socket.on('connect', () => {
      const users = localstorage.get('userconfig');
      self.sendMsg('login', users);
      console.log('connect success', self.socket.id);
    });

    this.socket.on('connecting', () => {
      console.log('正在连接...');
    });

    this.socket.on('disconnect', () => {
      console.log('disconnect');
    });

    this.socket.on('error', () => {
      console.log('连接错误...');
    });
  }

  public broadcast() {}

  public sendMsg(type: string, msg: any) {
    console.log('发送消息 >>>>>>>>>>>>>>>>>', type, msg);
    this.socket.emit(type, msg);
    eventBus.$emit('debug', {
      mtype: 'send',
      msg,
    });
    console.log('send Message:', msg);
  }
}

export default new socketMrg();
